package com.kt.delivery.config;

import com.kt.delivery.domain.User;
import com.kt.delivery.exception.ApiException;
import com.kt.delivery.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        if (token == null && token.equals("")){
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token信息不存在!");
            return false;
        }

        Boolean key = redisTemplate.hasKey("token:" + token);

        if (key){
            User user = (User) redisTemplate.opsForValue().get("token:" + token);
            // 获取openid
            RequestContextHolder.currentRequestAttributes().setAttribute("openId",user.getOpenId(), RequestAttributes.SCOPE_REQUEST);
            // 将用户信息存储在上下文中
            RequestContextHolder.currentRequestAttributes().setAttribute("user",user, RequestAttributes.SCOPE_REQUEST);
            return true;
        }



//        String sub = jwtUtil.validateToken(token);
//        if (sub == null && sub.equals("")){
//            log.info("token验证失败");
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token验证失败!");
//            return false;
//        }

        return false;
    }
}
